package com.bawei.module_mall.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bawei.module_mall.manager.OrderManager
import com.bawei.module_mall.model.Order

class OrderListViewModel : ViewModel() {

    private val _orders = MutableLiveData<List<Order>>()
    val orders: LiveData<List<Order>> = _orders

    private val _selectedTab = MutableLiveData(0)
    val selectedTab: LiveData<Int> = _selectedTab

    private val _message = MutableLiveData<String>()
    val message: LiveData<String> = _message

    init {
        loadOrders()
    }

    private fun loadOrders() {
        _orders.value = OrderManager.getAllOrders()
    }

    fun selectTab(position: Int) {
        _selectedTab.value = position
        filterOrdersByStatus(position)
    }

    private fun filterOrdersByStatus(tabPosition: Int) {
        val filteredOrders = when (tabPosition) {
            0 -> OrderManager.getAllOrders() // 全部
            1 -> OrderManager.getOrdersByStatus("待支付") // 待支付
            2 -> OrderManager.getOrdersByStatus("待发货") // 待发货
            3 -> OrderManager.getOrdersByStatus("已发货") // 待收货
            4 -> OrderManager.getOrdersByStatus("交易成功") // 待评价
            else -> emptyList()
        }
        _orders.value = filteredOrders
    }

    fun onAction1Click(order: Order) {
        when (order.action1Text) {
            "申请退款" -> {
                // 处理申请退款
                showMsg("申请退款功能待实现")
            }
            "删除订单" -> {
                // 处理删除订单
                OrderManager.deleteOrder(order.id)
                loadOrders() // 重新加载订单列表
                showMsg("订单已删除")
            }
            "取消订单" -> {
                // 处理取消订单
                OrderManager.updateOrderStatus(order.id, "已取消")
                loadOrders()
                showMsg("订单已取消")
            }
        }
    }

    fun onAction2Click(order: Order) {
        when (order.action2Text) {
            "确认收货" -> {
                // 处理确认收货
                OrderManager.updateOrderStatus(order.id, "交易成功")
                loadOrders()
                showMsg("确认收货成功")
            }
            "申请售后" -> {
                // 处理申请售后
                showMsg("申请售后功能待实现")
            }
            "立即支付" -> {
                // 处理立即支付
                OrderManager.updateOrderStatus(order.id, "待发货")
                loadOrders()
                showMsg("支付成功，等待发货")
            }
            "提醒发货" -> {
                // 处理提醒发货
                showMsg("已提醒商家发货")
            }
        }
    }

    private fun showMsg(msg: String) {
        _message.value = msg
    }

    // 刷新订单列表
    fun refreshOrders() {
        loadOrders()
    }
} 